<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </div>

    <!--<div style="margin-bottom: 10px;">
      <span style="font-weight: bold">调拨时间：</span>
      <a-checkable-tag style="font-size: 14px;margin: 5px;padding: 5px" v-for="(item,index) in this.allocateAndTransferDateList"
      :key="index" v-model:checked="item.checkedValue"
      @change="onChangeReceiptsDate(item.key,item.itemValue)">{{item.itemText}}
      </a-checkable-tag>
      <a-range-picker v-show="this.currentKey" @change="onChangeCustomerReceiptsDate" format="YYYY-MM-DD" v-model:value="dateValue"/>
    </div>

    <div style="margin-bottom: 10px;">
      <span style="font-weight: bold">订单状态：</span>
      <a-checkable-tag style="font-size: 14px;margin: 5px;padding: 5px" v-for="(item,index) in this.orderStatusList"
      :key="index" v-model:checked="item.checkedValue"
      @change="onChangeOrderStatus(item.key,item.itemValue)">{{item.itemText}}
      </a-checkable-tag>
    </div>

    <div style="margin-bottom: 10px;">
      <a-row>
        <a-col :span="6">
          <a-form-model-item label="调出仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="depositoryName">
            <a-select
              show-search
              :allowClear="true"
              placeholder="请选择仓库"
              option-filter-prop="children"
              v-model="queryParam.outDepository"
              style="width: 100%"
              :filter-option="filterOptionOutDepository"
              @change="changeOutDepository">
              <a-select-option :value="item.depositoryName" v-for="(item,index) in depositoryData" :key="index">
                {{item.depositoryName}}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :span="6">
          <a-form-model-item label="调入仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="depositoryName">
            <a-select
              show-search
              :allowClear="true"
              placeholder="请选择仓库"
              option-filter-prop="children"
              v-model="queryParam.inDepository"
              style="width: 100%"
              :filter-option="filterOptionInDepository"
              @change="changeInDepository">
              <a-select-option :value="item.depositoryName" v-for="(item,index) in depositoryData" :key="index">
                {{item.depositoryName}}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="创建人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplier">
            <a-tree-select
              style="width: 50%"
              :allowClear="true"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="departListData"
              :replaceFields="dataFields"
              placeholder="请选择部门"
              @change="changeDepart"
            >
            </a-tree-select>
            <span style="margin-left: 1%;margin-right: 1%">&#45;&#45;</span>
            <a-select
              show-search
              :allowClear="true"
              placeholder="请选择采购人员"
              option-filter-prop="children"
              v-model="queryParam.createBy"
              style="width: 30%;"
              :filter-option="filterOptionCreateBy"
              @change="changeCreateBy">
              <a-select-option :value="item.realname" v-for="(item,index) in createByData" :key="index">
                {{item.realname}}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
    </div>-->
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!--<a-button @click="addAllocateTransfer" type="primary" icon="plus">新增</a-button>-->
    </div>

    <!-- table区域-begin -->
    <div>
      <!--<div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{
        selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>-->

      <div class="list">
        <van-list
          v-model="loading"
          :finished="finished"
          offset="100"
          finished-text="没有更多了"
          @load="onLoadList"
          :immediate-check="false"
        >
          <div
            class="customer-list"
            v-for="(item,i) in dataSource"
            :key="i"
            @click="AllocateAndTransferDetail(item)"
          >
            <div>
              <div class="name">调拨编号：{{ item.allocateAndTransferNo || '无' }}</div>
              <div class="contact">
                <span>调拨日期：{{ item.allocateAndTransferTime || '无' }}</span>
              </div>
              <div class="contact">
                <span>出库仓库：{{ item.outDepository || '无' }}</span>
              </div>
              <div class="contact">
                <span>入库仓库：{{ item.inDepository || '无' }}</span>
              </div>
              <div class="contact">
                <span>调拨状态：
                  <a-tag v-if="item.status === 1">草稿</a-tag>
                  <a-tag color="orange" v-if="item.status === 2">审批中</a-tag>
                  <a-tag color="green" v-if="item.status === 3">审批通过</a-tag>
                  <a-tag color="red" v-if="item.status === 4">未通过</a-tag>
                  <a-tag color="magenta" v-if="item.status === 5">已撤销</a-tag>
                </span>
              </div>
            </div>
          </div>
        </van-list>
      </div>

      <!--<a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :customRow="setRow"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onSelectAll:onSelectAll,
          onSelect:onSelect,
          onChange: onSelectChange,
          type:'checkbox'
        }"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <a slot="allocateAndTransferNo" @click="AllocateAndTransferDetail(record)" slot-scope="text,record">{{ text }}</a>

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text,record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt=""
               style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="editAllocateTransfer(record)" v-if="record.status == 1  || record.status == 4">编辑</a>
          <a-divider type="vertical" v-if="record.status == 1 || record.orderStatus == 4"/>

          <a @click="AllocateAndTransferDetail(record)">详情</a>
          <a-divider type="vertical"/>

          <a-popconfirm title="确定撤销吗?" @confirm="() => revoke(record.id)" v-if="record.status == 1">
            <a>撤销</a>
          </a-popconfirm>

          <a-divider type="vertical" v-if="record.status == 1"/>
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>
        </span>
      </a-table>-->
    </div>

    <allocate-and-transfer-detail-modal ref="allocateAndTransferDetailModal"></allocate-and-transfer-detail-modal>
    <allocate-and-transfer-modal ref="allocateAndTransferModal" @ok="modalFormOk"></allocate-and-transfer-modal>

  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import {mixinDevice} from "../../../../utils/mixin";
  import {JeecgListMixin} from "../../../../mixins/JeecgListMixin";
  import {getAction, putAction} from "../../../../api/manage";
  import allocateAndTransferModal from "./modules/allocateAndTransferModal";
  import allocateAndTransferDetailModal from "./modules/allocateAndTransferDetailModal";

  export default {
    name: 'allocateAndTransferList',
    mixins: [JeecgListMixin, mixinDevice],
    components: {
      allocateAndTransferModal,allocateAndTransferDetailModal
    },
    data() {
      return {
        description: '供应链调拨管理管理页面',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '调拨单号',
            align: "center",
            dataIndex: 'allocateAndTransferNo',
            slots: { title: 'customTitle' },
            scopedSlots: { customRender: 'allocateAndTransferNo' },
          },
          {
            title: '调拨日期',
            align: "center",
            dataIndex: 'allocateAndTransferTime'
          },
          {
            title: '出库仓库',
            align: "center",
            dataIndex: 'outDepository'
          },
          {
            title: '入库仓库',
            align: "center",
            dataIndex: 'inDepository'
          },
          {
            title: '状态',
            align: "center",
            dataIndex: 'status',
            customRender:function (text) {
              if (text == 1){
                return <a-tag>草稿</a-tag>
              }else if(text == 2){
                return <a-tag color="orange">审核中</a-tag>
              }else if (text == 3){
                return <a-tag color="green">审核通过</a-tag>
              }else {
                return <a-tag color="magenta">已撤销</a-tag>
              }
            }
          },
          {
            title: '备注',
            align: "center",
            dataIndex: 'remark'
          },
          {
            title: '创建人',
            align: "center",
            dataIndex: 'createBy'
          },
          {
            title:'审批原因',
            align:"center",
            dataIndex: 'reason',
            ellipsis: true,
            scopedSlots: { customRender: 'reason' },
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            width:200,
            scopedSlots: {customRender: 'action'}
          }
        ],
        /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
        queryParam: {},
        model:{},
        url: {
          list: "/ghSupplychainAllocateAndTransfer/list",
          edit: "/ghSupplychainAllocateAndTransfer/edit",
          delete: "/ghSupplychainAllocateAndTransfer/delete",
          deleteBatch: "/ghSupplychainAllocateAndTransfer/deleteBatch",
          itemList: "/ghSupplychainAllocateAndTransferItem/list",

          getSearchConditionData: "/ghSupplychainAllocateAndTransfer/getQueryCriteriaData",
          queryDepositoryList: "/ghSupplychainDepository/allList",
          queryUserList: "/erp/user/selectUserByDepartId",
          queryDepartTreeList: "/erp/user/selectDepartTreeList",
        },
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        dictOptions: {},
        superFieldList: [],
        currentKey: false,
        startDate: '',
        endDate: '',
        dateValue: [],
        depositoryData: [], //仓库列表
        createByData:[],    //创建人列表
        currentReceiptsType: 0,
        currentAllocateAndTransferTime: '',
        currentOrderStatus: 0,
        allocateAndTransferDateList:[],  //搜索条件：调拨时间
        orderStatusList:[],   //搜素条件：订单状态
        selectedRowKeys: [],
        selectedRows: [],
        dataFields: {
          title: 'departName',
          key: 'id',
          value: 'id',
          children: "children"
        },
        currentDepartId: "",  //当前所选部门
        departListData:[],    //部门列表
        finished: false,
      }
    },
    created() {
      this.initSearchConditionData();
      this.loadDepartTreeListData();
      this.loadDepositoryData();
    },
    computed: {
      importExcelUrl: function () {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      revoke(id){
        var that = this;
        let params = {};
        params.id = id;
        params.status = 5;
        putAction(this.url.edit,params).then((res =>{
          if (res.success){
            that.$message.success(res.message);
            that.loadData();
          }else {
            that.$message.warning(res.message);
          }
        }))
      },
      //新增调拨单
      addAllocateTransfer(){
        this.$refs.allocateAndTransferModal.title = "新增调拨单"
        this.$refs.allocateAndTransferModal.addAllocateTransfer();
        this.$refs.allocateAndTransferModal.loadDepositoryData();
      },
      //编辑调拨单
      editAllocateTransfer(record){
        this.$refs.allocateAndTransferModal.title = "修改调拨单"
        this.$refs.allocateAndTransferModal.editAllocateTransfer(record);
        this.$refs.allocateAndTransferModal.loadDepositoryData();
        //loadMaterialStock
        //this.$refs.allocateAndTransferModal.loadMaterialStock();
      },
      AllocateAndTransferDetail(record){
        this.$refs.allocateAndTransferDetailModal.title = "调拨单详情";
        this.$refs.allocateAndTransferDetailModal.showDetail(record);
      },
      //加载用户列表
      loadUserListData() {
        getAction(this.url.queryUserList,{departId:this.currentDepartId}).then((res) => {
          if (res.success) {
            this.createByData = res.result.records||res.result;
          }
        })
      },

      //加载仓库
      loadDepositoryData(){
        getAction(this.url.queryDepositoryList).then((res) => {
          if (res.success) {
            this.depositoryData = res.result.records||res.result;
          }else{
            this.$message.warning(res.message)
          }
        })
      },

      changeOutDepository(value){
        this.loadData();
      },
      changeInDepository(value){
        this.loadData();
      },
      changeCreateBy(value){
        this.loadData();
      },

      filterOptionOutDepository(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      filterOptionInDepository(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },

      filterOptionCreateBy(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },


      initSearchConditionData() {
        getAction(this.url.getSearchConditionData).then(res => {
          if (res.success) {
            this.allocateAndTransferDateList = res.result.allocateAndTransferDateList;
            this.orderStatusList = res.result.orderStatusList;
          }
        })
      },

      //调拨时间发生变化
      onChangeReceiptsDate(key, itemValue){
        for (let i = 0; i < this.allocateAndTransferDateList.length; i++) {
          if (key == this.allocateAndTransferDateList[i].key) {
            this.allocateAndTransferDateList[i].checkedValue = true;
          } else {
            this.allocateAndTransferDateList[i].checkedValue = false;
          }
        }
        if (key == 'key9'){
          this.currentKey = true;
        }else {
          this.currentKey = false;
          this.dateValue = [];
          this.currentAllocateAndTransferTime = itemValue;
          this.loadData();
        }
      },
      //自定义单据时间
      onChangeCustomerReceiptsDate(value, dateString){
        this.startDate = dateString[0];
        this.endDate = dateString[1];
        this.currentAllocateAndTransferTime = "customizeTime";
        this.loadData();
      },
      //订单状态发生变化
      onChangeOrderStatus(key, itemValue){
        for (let i = 0; i < this.orderStatusList.length; i++) {
          if (key == this.orderStatusList[i].key) {
            this.orderStatusList[i].checkedValue = true;
          } else {
            this.orderStatusList[i].checkedValue = false;
          }
        }
        this.currentOrderStatus = itemValue;
        this.loadData();
      },
      onLoadList(e){
        this.ipagination.current++
        this.loadData(this.ipagination.current)
      },
      loadData(arg) {
        if(!this.url.list){
          this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
          this.dataSource = []
          this.finished = false;
        }
        var params = this.getQueryParams();//查询条件
        this.loading = true;
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = [...this.dataSource, ...res.result.records]
            if(res.result.total)
            {
              this.ipagination.total = res.result.total;
            }else{
              this.ipagination.total = 0;
            }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }else{
            this.$message.warning(res.message)
          }
          if(res.result.records.length<10){
            this.finished = true;
          }
        }).finally(() => {
          this.loading = false
        })
      },
      /*loadData(arg) {
        var params = this.getQueryParams();//查询条件

        this.loading = true;
        if (this.currentAllocateAndTransferTime != null && this.currentAllocateAndTransferTime != '') {
          params.currentAllocateAndTransferTime = this.currentAllocateAndTransferTime;
          if (this.currentAllocateAndTransferTime == "customizeTime"){
            params.beginTime = this.startDate;
            params.endTime = this.endDate;
          }
        }else {
          params.currentAllocateAndTransferTime = "";
        }

        if (this.currentOrderStatus != null && this.currentOrderStatus != '' && this.currentOrderStatus != 0) {
          params.status = this.currentOrderStatus;
        }else {
          params.status = "";
        }

        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records||res.result;
            if(res.result.total)
            {
              this.ipagination.total = res.result.total;
            }else{
              this.ipagination.total = 0;
            }
          }else{
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.loading = false
        })
      },*/
      modalFormOk(){
        this.loadData();
      },
      onSelectAll(selected, selectedRows, changeRows) {
        if(selected) {
          let rows = [...selectedRows]
          this.selectedRows = this.selectedRows.concat(rows)
        } else {
          changeRows.forEach(item => {
            const delIndex = this.selectedRows.findIndex((val) => {
              return val.id === item.id
            })
            this.selectedRows.splice(delIndex, 1)
          })
        }
      },
      onSelect(record, selected) {
        if(selected) {
          this.selectedRows.push(record);
        } else {
          const delIndex = this.selectedRows.findIndex((val) => {
            return val.id === record.id
          })
          this.selectedRows.splice(delIndex,1)
        }
      },
      onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys;
      },
      //表格行点击事件
      setRow (record) {
        return {
          on: {
            click: () => {
              let flag = false
              let keys = [];
              keys = this.selectedRowKeys;
              if(keys.indexOf(record.id) >= 0) {
                flag=true
              }
              if(flag){
                keys.splice(keys.findIndex(item => item === record.id), 1)
                this.selectedRows.splice(this.selectedRows.findIndex(item => item === record.id),1)
              } else {
                keys.push(record.id)
                this.selectedRows.push(record);
              }
            }
          }
        }
      },
      //加载部门树形列表
      loadDepartTreeListData(){
        getAction(this.url.queryDepartTreeList).then((res) => {
          if (res.success) {
            this.departListData = res.result.records||res.result;
          }
        })
      },
      changeDepart(value){
        this.currentDepartId = value;
        this.loadUserListData();
      },
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';

  .remarkTxt{
    max-width: 350px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  /deep/ .van-dropdown-menu__bar{
    height: 30px;
    box-shadow: none;
    border: 1px solid lightgrey;
    border-radius: 5px;
  }

  .list{
    overflow-y: scroll;
    height:100vh;
  }
  ::-webkit-scrollbar {
    display: none;
  }
  .customer-list {
    align-items: center;
    border-top: 1px solid #d9d9d9;
    /*height: 120px;*/
  }
  .name{
    margin-top: 10px;
    margin-bottom: 5px;
    font-size: 13px;
    color: #161616;
    line-height: normal;
  }
  .contact{
    font-size: 12px;
    color: #a39f9f;
    margin-bottom: 5px;
  }
</style>